#include "FloorSaw.h"

#include "GamePlayState.h"

// Constructor
FloorSaw::FloorSaw(void) : Vertical(false), Horizontal(false)
{
	// Set the hazard type
	HzType = HZ_SAW;

	// Set which image portion to use
	image.top = 0;
	image.left = image.bottom = 32;
	image.right = 64;
}

// Destructor
FloorSaw::~FloorSaw(void) { }

// Draw
void FloorSaw::Render(void)
{
	// Get the camera
	int camx = GamePlayState::GetInstance()->GetCamX();
	int camy = GamePlayState::GetInstance()->GetCamY();

	// Don't draw if it's off screen
	if( GetX() < camx || GetY() < camy || GetX() > camx + 800 || GetY() > camy + 600)
		return;

	// Do the basic rendering
	Hazard::Render();

	// Flush
	CSGD_Direct3D::GetInstance()->GetSprite()->Flush();
}

// Update
void FloorSaw::Update(float elapsedTime)
{
	// Get the camera
	int camx = GamePlayState::GetInstance()->GetCamX();
	int camy = GamePlayState::GetInstance()->GetCamY();

	// Don't update if it isn't onscreen
	if( GetX() < camx || GetY() < camy || GetX() > camx + 800 || GetY() > camy + 600 )
		return;

	// Lower the health of things colliding with it
	for(unsigned int i = 0; i < Collisions.size(); ++i)
	{
		if( Collisions[i]->GetType() == OBJ_PLAYER )
			((Player*)Collisions[i])->TakeDam(10*elapsedTime);
		if( Collisions[i]->GetType() == OBJ_ENEMY )
		{
			Enemy* e = (Enemy*)(Collisions[i]);
			e->SetHealth(e->GetHealth() - 10*elapsedTime);
		}
		Collisions[i]->Release();
	}

	// Move based on direction
	switch( GetDirection() )
	{
	case 0:
		SetY(GetY() + 50*elapsedTime);
		break;
	case 1:
		SetY(GetY() - 50*elapsedTime);
		break;
	case 2:
		SetX(GetX() + 50*elapsedTime);
		break;
	case 3:
		SetX(GetX() - 50*elapsedTime);
		break;
	}

	// Clear out the list of collisions
	Collisions.clear();
}

// Collision Checking
bool FloorSaw::CheckCollision(IEntity* base)
{
	if( Entity::CheckCollision(base) )
	{
		// Do damage to bots that touch the saws
		if( base->GetType() == OBJ_PLAYER || base->GetType() == OBJ_ENEMY )
		{
			Collisions.push_back((Entity*)base);
			((Entity*)(base))->AddRef();
			return true;
		}

		// Change direction when hitting a wall
		if( base->GetType() == OBJ_TILE )
		{
			if( GetDirection() == 0 || GetDirection() == 2 )
			{
				SetDirection(GetDirection() + 1);
				Vertical ? SetY(GetY() - 25) : SetX(GetX() - 25);
			}
			else
			{
				SetDirection(GetDirection() - 1);
				Vertical ? SetY(GetY() + 25) : SetX(GetX() + 25);
			}
			return true;
		}
	}
	return false;
}

// Make the saw move
void FloorSaw::Activate(bool vert)
{
	Vertical = vert;
	Horizontal = !vert;
	vert ? SetDirection(0) : SetDirection(2);
}